import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Navigator, Image} from '@tarojs/components'
import './order.scss'
import { CityLocation, OrderItem, DistributorOrder, DistributorOrderStatistics } from '../../utils/server.interface'
import { ComponentClass } from 'react'
import { connect } from 'react-redux'
import { AtNoticebar } from 'taro-ui'
import { NEW_DISTRIBUTOR_ORDER, NEW_DISTRIBUTOR_ORDER_STATISTICS } from '../../constants/api'
import { user } from '../../utils/user.service';
import {getHeadTop, GetRequest,vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  tabIndex: number
  loadMoreStatus: "more" | "loading" | "noMore"
  curTabIndex: number
  orderList: DistributorOrder[]
  searchKey: string
  statistics: DistributorOrderStatistics
  searchBarTop: number
  noticeShow: number
  parentOrderId: string
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Order {
  props: IProps
}

@connect(({location})=>({
  location
}),(dispatch)=>({

}))


class Order extends Component {
  tabList = [{ title: '全部', value: -1 }, { title: '已付款', value: 1 }, { title: '已完成', value: 2 },{ title: '待使用', value: 55 }, { title: '已退款', value: 4 }]
  state: PageState = {
    tabIndex: 0,
    noticeShow: 0,
    loadMoreStatus: 'loading',
    curTabIndex: 0,
    orderList: [],
    searchKey: '',
    statistics: {
      allPayCount: 0,
      cancelPayCount: 0,
      finishCount: 0,
      offPayCount: 0,
      toBeUseCount:0,
      onPayCount: 0
    },
    searchBarTop:0,
    parentOrderId:''
  }
  page = 1
  async onReachBottom() {
    if(this.state.loadMoreStatus != 'noMore') {
      this.setState({ loadMoreStatus: 'loading'})
      this.page++
      const orderList = await this.getData(this.page)
      const old = this.state.orderList
      if(orderList){
        this.setState({orderList: [...old, ...orderList]})
      }
    }
  }
  tabClick(index) {
    this.page = 1
    this.setState({ curTabIndex: index, loadMoreStatus: 'loading', orderList: [] }, async () => {
      const orderList = await this.getData(this.page)
      this.setState({orderList})
    })
  }
  noticeClose() {
    this.setState({ noticeShow: 0 })
  }
  async UNSAFE_componentWillMount() {
    if(process.env.TARO_ENV==='h5'){
      await h5Wx.getConfig()
    }
    const { parentOrderId } = Taro.getCurrentInstance().router.params
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 40) : (headTop.statusBar + headTop.top + 50)
    this.setState({
      searchBarTop,
      parentOrderId
    })
    const isLogin = await user.checkLogin()
    if(!isLogin){
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({ url: '/pages/my/index/index' })
      }, 1500)
      return
    }
    const noticeShow =Taro.getCurrentInstance().router.params.noticeShow || 0
    this.setState({noticeShow})
    const status = parseInt(Taro.getCurrentInstance().router.params.status)
    let index = 0
    this.tabList.forEach((item, i) => {
      if(item.value === status) index = i
    })
    Taro.showLoading({title: '加载中...'})
    this.tabClick(index)
    // const setting = await platform.getSetting()
    // if(setting) {
    //     Taro.setNavigationBarTitle({
    //         title: setting.platformName || ''
    //     })
    // }
    const delEnd = noticeShow==1?true:false
    const statistics = await newHttp.catchGet<DistributorOrderStatistics>(NEW_DISTRIBUTOR_ORDER_STATISTICS, {delEnd})
    if(statistics){
      this.setState({ statistics })
    }
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }
  async componentDidShow() {
    vcmonitor(this)
  }
  async getData(page) {
    const index = this.state.curTabIndex
    const delEnd = this.state.noticeShow==1?true:false
    const orderList = await newHttp.catchGet<OrderItem[]>(NEW_DISTRIBUTOR_ORDER, {parentOrderId:this.state.parentOrderId,pageNumber: page, orderStatus: this.tabList[index].value, searchKeywords: this.state.searchKey,delEnd})
    if(orderList && orderList.length === 10){
      this.setState({ loadMoreStatus: 'more'})
    } else {
      this.setState({ loadMoreStatus: 'noMore'})
    }
    return orderList
  }
  searchChange(value) {
    this.setState({ searchKey: value })
  }
  searchClear() {
    this.setState({ searchKey: '', orderList: [], loadMoreStatus:'loading'}, async () => {
      const orderList = await this.getData(this.page)
      this.setState({orderList})
    })
  }
  search() {
    this.page = 1
    this.setState({ loadMoreStatus: 'loading', orderList: []}, async () => {
      const orderList = await this.getData(this.page)
      if(orderList){
        this.setState({orderList})
      }
    })
  }
  jumpOther(nu){
    Taro.navigateToMiniProgram({
      appId:'wx6885acbedba59c14',
      path:`pages/result/result?nu=${nu}`
    })
  }
  render() {
    const { searchBarTop,curTabIndex, loadMoreStatus, orderList, searchKey, statistics,noticeShow } = this.state
    return (
      <View className='dist-order-list-root'>
        <GzhAuth />
        {/*<View className="head-bg" style={`height: ${searchBarTop}Px;`}>*/}
        {/*  <SearchBar color={"#333"} value={searchKey} searchChange={this.searchChange.bind(this)} searchClear={this.searchClear.bind(this)} search={this.search.bind(this)}></SearchBar>*/}
        {/*</View>*/}
        {/*<AtTabs className={"order-tabs"} tabList={this.tabList} current={curTabIndex} onClick={this.tabClick.bind(this)}></AtTabs>*/}
        {!!noticeShow && <AtNoticebar close onClose={this.noticeClose.bind(this)}><View>提醒：待提金额--是指待使用订单核销后的佣金, 待用户核销后佣金自动转移到可提金额里</View></AtNoticebar>}
        <view>
          {orderList.map(item => <View key={item.id} className='order-item'>
            <Navigator  url={`/distributor/order/detail?orderId=`+item.id}>
              <View className='head'>
                <View className='status'>{item.status_name}</View>
              </View>
              <View className='order-info'>
                <Image className='img' src={item.default_img_url} mode='aspectFill'></Image>
                <View className='name-box'>
                  <View className='name'>{item.is_meal===1 && <Text style='color:red;'>[套餐]</Text>}{item.product_name}</View>
                  {!!item.memo && <View className='valid-date'>{item.memo}</View>}
                  <View className='date'>{item.add_date}</View>
                </View>
                <View className='order-info-right'>
                  <View className='order-info-num'>x{item.buy_amount}</View>
                  {item.pay_source_img && <Image className='order-info-from' src={item.pay_source_img}></Image>}
                </View>
              </View>
              <View className='total'>
                <View className='title'><Text decode>{item.linkman}</Text></View>
                <View className='price-box'>
                  {!!item.estimated_earnings && item.status!==99 && item.status!==4 &&  <View className='shouyi'>
                    {item.status == 1 && <Text>预估收益:￥</Text>}
                    {item.status == 2 && <Text>收益:￥</Text>}
                    <Text className='bag'>{item.estimated_earnings}</Text>
                  </View>}
                  <View className='price'>￥<Text>{item.total_fee}</Text></View></View>
              </View>
            </Navigator>
            <View className='btn-box' style={`${item.isSendSms!==1 && 'border-top:none;'}`}>
              <View className='btn-item-box'>
                {item.express_no && <View className='btn-item primary' onClick={this.jumpOther.bind(this,item.express_no)}>查看物流</View>}
              </View>
              <View className='btn-item-box'>
                {item.isSendSms==1 && <View className='btn-item primary'>重发短信</View>}
              </View>
            </View>
          </View>)}
        </view>
      </View>
    )
  }
}

export default Order as ComponentClass<PageOwnProps, PageState>
